﻿using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Runtime.InteropServices;
using UnityEngine;
using YanhuaMMO;
using LitJson;
using Assets.U8SDK;
using LuaInterface;
using TapTap.Bootstrap;
using TapTap.Common;
using TapTap.Moment;
using TapTap.Login;
//using UnityNative.Toasts.Example;

public class LoginSDK : MonoBehaviour
{
    private string mPlatform; //平台名字
    private int mAccountType;
    private string mTDGAAppId;
    private string mChannel;

    private bool u8Init = false;

    private U8SDK _u8SDK;
    private U8SDK u8SDK 
    {
        get 
        {
            if (Application.platform != RuntimePlatform.WindowsPlayer && Application.platform != RuntimePlatform.WindowsEditor 
                                                                      && Application.platform != RuntimePlatform.OSXEditor
                                                                      && Application.platform != RuntimePlatform.OSXPlayer)
                if (_u8SDK == null)
                    _u8SDK = new U8SDK();
            return _u8SDK;
        }
    }
    AndroidJavaObject u8SdkModule;
    public string getPlatform()
    {
        return mPlatform;
    }
    public int getAccountType()
    {
        return mAccountType;
    }
    public string getTDGAAppId()
    {
        return mTDGAAppId;
    }

    public string getChannel()
    {
        return mChannel;
    }

#if SDK_BILIBILI
    protected static AndroidJavaClass mAndroidObject;
    protected static AndroidJavaClass androidObject{
        get{
            if(mAndroidObject == null)
            {
                mAndroidObject = new AndroidJavaClass("com.bsgamesdk.android.BSGameSdkCenter");
            }
            return mAndroidObject;
        }
    }

    private bool isInit =false;

    protected static int SUCCESS_CODE = 10010;  //成功
#elif SDK_XN
    protected static AndroidJavaObject mAndroidObject;
    protected static AndroidJavaObject androidObject
    {
        get
        {
            if(mAndroidObject == null)
            {
                AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
                mAndroidObject = jc.GetStatic<AndroidJavaObject>("currentActivity");
            }
            return mAndroidObject;
        }
    }

    private bool isInit =false;
    protected static int SUCCESS_CODE = 10010;  //成功

#endif


    private static LoginSDK instance;

#if UNITY_IPHONE
    [DllImport("__Internal")]
    private static extern void ShowAccountCenterIOS();

    [DllImport("__Internal")]
    private static extern void loginIOS();

    [DllImport("__Internal")]
    private static extern void loginOutIOS();
    
    [DllImport("__Internal")]
    private static extern void payIOS(string productId, string productName, string productDesc, int price, int buyNum,
                                                               int coinNum, string serverID, string serverName, string roleID, string roleName,
                                                               int roleLevel, string vip, string payNotifyUrl, string extension);
    
    [DllImport("__Internal")]
    private static extern void submitExtraDataIOS(int dataType, string roleId, string roleName, string level, int serverId , string serverName );
    [DllImport("__Internal")]
    private static extern void initTADataAppIdIOS(string appid);
    //微信分享相关start=====
    [DllImport("__Internal")]
    private static extern void ShareImgToWX(int scene, byte[] imageByte, int arrayLength, string title, string description);
    //微信分享相关end=======
    //微博图片分享
    [DllImport("__Internal")]
    private static extern void ShareImgToWeibo(byte[] imageByte, int arrayLength, string title);
    [DllImport("__Internal")]
    private static extern void setIconBadgeNumber(int number);
    //融云相关
    [DllImport("__Internal")]
    private static extern void initIM(string appKey);
    [DllImport("__Internal")]
    private static extern void connectIM(string token);
    [DllImport("__Internal")]
    private static extern void disconnectIM();
    [DllImport("__Internal")]
    private static extern void logoutIM();
    [DllImport("__Internal")]
    private static extern void joinChatRoom(string chatRoomId, int defMsgCount);
    [DllImport("__Internal")]
    private static extern void quitChatRoom(string chatRoomId);
    [DllImport("__Internal")]
    private static extern void setMySelfUserInfo(string userid, string userName, string portraitUrl, string extra);

    [DllImport("__Internal")]
    private static extern void sendMessageIM(string txtmsg, string targetID, int conversationType);

    [DllImport("__Internal")]
    private static extern void removeConversation(string targetId, int conversationType);

    [DllImport("__Internal")]
    private static extern void getHistoryMessagesIM(string targetId, int conversationType, long lastMsgId, int count);
    [DllImport("__Internal")]
    private static extern void getChatRoomInfo(string chatRoomId, int defMemberCount);

    // iOS Widget功能相关接口
    [DllImport("__Internal")]
    private static extern void initUserData(string nick, long tick, int maxHangTime, long power, int stage, int tower, int heros);
    [DllImport("__Internal")]
    private static extern void setUserNick(string nick);
    [DllImport("__Internal")]
    private static extern void setUserGetRewardTick(long tick, int maxHangTime);
    [DllImport("__Internal")]
    private static extern void setUserPower(long power);
    [DllImport("__Internal")]
    private static extern void setUserStage(int stage);
    [DllImport("__Internal")]
    private static extern void setUserTower(int tower);
    [DllImport("__Internal")]
    private static extern void setUserHeros(int heros);
#endif

    public static LoginSDK GetInstance()
    {
        return instance;
    }

    private void Awake()
    {
        instance = this;
        TA.TABehavior.Init();
        InitTADataAppId();

        var config = new TapConfig.Builder()
           .ClientID("nIfoGZfm3MwZLZJLXg")  // 必须，开发者中心对应 Client ID
           .ClientToken("0No0h7OBVeqWVBkuMrafyye2XcZaB7LapXNcnaej")  // 必须，开发者中心对应 Client Token
           .ServerURL("https://nifogzfm.cloud.tds1.tapapis.cn") // TapDC 后台获取
           .RegionType(RegionType.CN)  // 非必须，默认 CN 表示国内
           .ConfigBuilder();
        TapBootstrap.Init(config);
        TapLogin.Init("nIfoGZfm3MwZLZJLXg");
        TapMoment.Init("nIfoGZfm3MwZLZJLXg");

        TapMoment.SetCallback((code, msg) =>
        {
            Debug.Log("---- moment 回调  code: " + code + " msg: " + msg + "----");
            if (code == 20100)
            {
                //UnityNativeToastsHelper.ShowShortText("获取新消息失败");
            }
            else if (code == 20000)
            {
                //UnityNativeToastsHelper.ShowShortText("获取新消息成功: " + msg);
            }
            else if (code == 30000)  //进入动态社区
            {
                WwiseManager.Instance.SetVolume(0, (int)WwiseManager.WwiseFlagEnum.Music);
            }
            else if (code == 30100)  //从动态返回游戏
            {
                Debug.LogError("=============从动态返回游戏============");
                string s_Volume = YanhuaMMO.Util.GetPlayerPrefs("wwise_music_volume");
                if (s_Volume != null && System.Convert.ToInt32(s_Volume) > 0)
                {
                    WwiseManager.Instance.SetVolume(System.Convert.ToInt32(s_Volume), (int)WwiseManager.WwiseFlagEnum.Music);
                }
                Screen.orientation = ScreenOrientation.Portrait;
                LuaHelper.GetLuaManager().CallFunc("OutFromTaptap");
            }
        });

        //if(Application.platform == RuntimePlatform.Android)
        //{
        //    AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        //    AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
        //    mPlatform = jo.Get<string>("s_platform");
        //    mTDGAAppId = jo.Get<string>("s_tdgaAppId");
        //    mChannel = jo.Get<string>("s_tdgaChannel");
        //}
        //else
        //{
        //    mPlatform = "uzone";
        //    if(Application.platform == RuntimePlatform.IPhonePlayer)
        //    {
        //        mTDGAAppId = "8268BF286C29457FABB289F4C35A04A4";
        //        mChannel = "ios";
        //    }
        //    else
        //    {
        //        mTDGAAppId ="";
        //        mChannel ="";
        //    }
        //}

    }
	public void OnDestroy()
	{
		Util.CallMethod("SDKManager", "IMDisconnect");
	}

    private void OnApplicationQuit()
    {
        //TA.TABehavior.Track("logout", "");
        TA.TABehavior.LoginOut();
        LoginSDK.GetInstance().SubmitExtraData(5);
    }

    public bool IsU8Init()
    {
#if UNITY_IOS
        return u8Init;
#endif
        return u8SDK.GetU8InitSuccess();
    }

    // U8SDK登录
    public void LoginU8SDK()
    {
#if UNITY_EDITOR
        //u8SDK.LoginIn();
#elif UNITY_ANDROID
        u8SDK.LoginIn();
#elif UNITY_IOS
        Debug.LogError("loginIOS========unity");
        loginIOS();
#endif
//        if (Application.platform != RuntimePlatform.WindowsPlayer && Application.platform != RuntimePlatform.WindowsEditor 
//                                                                  && Application.platform != RuntimePlatform.OSXEditor
//                                                                  && Application.platform != RuntimePlatform.OSXPlayer)
//        {
//            u8SDK.LoginIn();
//        }
//#if UNITY_IPHONE
//            Debug.LogError("loginIOS========unity");
//            loginIOS();
//#endif
    }

    public void LoginOutU8SDK() 
    {
#if UNITY_EDITOR
        //u8SDK.LoginOut();
#elif UNITY_ANDROID
        u8SDK.LoginOut();
#elif UNITY_IOS
        Debug.LogError("loginOutIOS========unity");
        loginOutIOS();
#endif
//        if (Application.platform != RuntimePlatform.WindowsPlayer && Application.platform != RuntimePlatform.WindowsEditor 
//                                                                  && Application.platform != RuntimePlatform.OSXEditor
//                                                                  && Application.platform != RuntimePlatform.OSXPlayer)      
//        {
//            u8SDK.LoginOut();
//        }
//#if UNITY_IPHONE
//            Debug.LogError("loginOutIOS========unity");
//            loginOutIOS();
//#endif
    }
    public void InitTADataAppId()
    {
#if UNITY_IPHONE
        string appid = ThinkingAnalytics.ThinkingAnalyticsAPI.GetDistinctId();
        Debug.LogError("InitTADataAppId========unity==" + appid);
        initTADataAppIdIOS(appid);
#endif
    }
    public int GetCurChannel() 
    {
        if (AppConst.forceChannel > 0)
        {
#if UNITY_IOS
            return AppConst.forceChannel;
#elif UNITY_ANDROID
            return AppConst.forceChannel;
#endif
        }
#if UNITY_EDITOR
        if (u8SDK != null)
        {
            return u8SDK.GetCurChannel();
        }
#elif UNITY_ANDROID
        if (u8SDK != null)
        {
            return u8SDK.GetCurChannel();
        }
#elif UNITY_IOS
        return 100;
#endif
        return 1;
    }
    public string GetSubChannel()
    {
#if UNITY_EDITOR
        if (u8SDK != null)
        {
            return u8SDK.GetSubChannel();
        }
#elif UNITY_ANDROID
        if (u8SDK != null)
        {
            return u8SDK.GetSubChannel();
        }
#elif UNITY_IPHONE
        return "100";
#endif

        return "normal";
    }
    /// <summary>
    /// 安卓手机退出键
    /// </summary>
    public void ExitU8SDK()
    {
        if (Application.platform == RuntimePlatform.Android)
        {
            u8SDK.Exit();
        }
    }
    /// <summary>
    /// 直接退出
    /// </summary>
    public void ExitDirectlyU8SDK()
    {
        if (Application.platform == RuntimePlatform.Android)
        {
            u8SDK.ExitDirectly();
        }
    }
	public void AnalyticsTrackEventByU8SDK(string eventCode, string eventName, string extension = null)
    {
        if (Application.platform != RuntimePlatform.WindowsPlayer && Application.platform != RuntimePlatform.WindowsEditor 
                                                                  && Application.platform != RuntimePlatform.OSXEditor
                                                                  && Application.platform != RuntimePlatform.OSXPlayer)
        {
            u8SDK.AnalyticsTrackEvent(eventCode, eventName, extension);
        }
    }
    /// <summary>
    /// 提交额外数据
    /// </summary>
    /// <param name="dataType">1：选择服务器（选接） 2：创建角色 3：进入游戏 4：等级提升 5：退出游戏</param>
    /// <param name="roleId"></param>
    /// <param name="roleName"></param>
    /// <param name="level"></param>
    /// <param name="serverId"></param>
    /// <param name="serverName"></param>
    public void SubmitExtraData(int dataType, string roleId = "123", string roleName = "Name_123", string level = "1", int serverId = 1, string serverName = "server_1")
    {
        if (Application.platform != RuntimePlatform.WindowsPlayer && Application.platform != RuntimePlatform.WindowsEditor 
                                                                  && Application.platform != RuntimePlatform.OSXEditor
                                                                  && Application.platform != RuntimePlatform.OSXPlayer)
        {
            u8SDK.SubmitExtraData(dataType, roleId, roleName, level, serverId, serverName);
        }
#if UNITY_IPHONE
        Debug.LogError("submitExtraDataIOS====unity");
        submitExtraDataIOS(dataType, roleId, roleName, level, serverId, serverName);
#endif
    }
    /// <summary>
    /// 支付
    /// </summary>
    /// <param name="productId">充值商品ID，游戏内的商品ID</param>
    /// <param name="productName">商品名称，比如100元宝，500钻石...</param>
    /// <param name="productDesc">商品描述，比如 充值100元宝，赠送20元宝</param>
    /// <param name="price">充值金额(单位：元)</param>
    /// <param name="buyNum">购买数量，一般都是1</param>
    /// <param name="coinNum">玩家当前身上剩余的游戏币</param>
    /// <param name="serverID">玩家所在服务器的ID</param>
    /// <param name="serverName">玩家所在服务器的名称</param>
    /// <param name="roleID">玩家角色ID</param>
    /// <param name="roleName">玩家角色名称</param>
    /// <param name="roleLevel">玩家角色等级</param>
    /// <param name="vip">玩家vip等级</param>
    /// <param name="payNotifyUrl">游戏服务器支付回调地址，渠道SDK支付成功，异步通知U8Server，U8Server根据该地址，通知游戏服务器发货</param>
    /// <param name="extension">支付成功之后，U8Server原样返回给游戏服务器</param>
    public void PayU8SDK(string productId, string productName, string productDesc, int price, int buyNum,
                            int coinNum, string serverID, string serverName, string roleID, string roleName,
                            int roleLevel, string vip, string payNotifyUrl, string extension)
    {
        if (Application.platform != RuntimePlatform.WindowsPlayer && Application.platform != RuntimePlatform.WindowsEditor 
                                                                  && Application.platform != RuntimePlatform.OSXEditor
                                                                  && Application.platform != RuntimePlatform.OSXPlayer)
        {
            if(u8SDK != null)
            {
                u8SDK.Pay(productId, productName, productDesc, price, buyNum,
                            coinNum, serverID, serverName, roleID, roleName,
                            roleLevel, vip, payNotifyUrl, extension);
            }
        }
#if UNITY_IPHONE
        Debug.LogError("payIOS====unity");
        payIOS(productId, productName, productDesc, price, buyNum,
            coinNum, serverID, serverName, roleID, roleName,
            roleLevel, vip, payNotifyUrl, extension);
#endif

    }

    // Use this for initialization
    void Start()
    {
    }


    // Update is called once per frame
    void Update()
    {

    }


    // 游戏发送消息

    public void exit()
    {
        if (AppConst.isBussiness || AppConst.DebugMode)
            return;

        if (Application.platform == RuntimePlatform.Android)
        {
#if SDK_BILIBILI
            androidObject.CallStatic("exit");
#elif SDK_XN
#endif
        }
    }

    public void loginAccount()
    {
        if (AppConst.isBussiness || AppConst.DebugMode)
            return;

        if (Application.platform == RuntimePlatform.Android)
        {
#if SDK_BILIBILI
            if(isInit)
            {
                androidObject.CallStatic("login");
            }
            else
            {
                androidObject.CallStatic("init");
            }
#elif SDK_XN
            if(!isInit)
            {
                androidObject.Call("initSDK");
                isInit = true;
            }
            androidObject.Call("login");
#endif
        }
        else if (Application.platform == RuntimePlatform.IPhonePlayer)
        {
#if UNITY_IPHONE
            //login();
#endif
        }
    }

    public void activeAccount()
    {
        //if (Application.platform == RuntimePlatform.Android)
        //{
        //    AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        //    AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
        //    jo.Call("activeAccount");
        //}
        //else if (Application.platform == RuntimePlatform.IPhonePlayer)
        //    activeGameAccount();
    }

    public void logOut()
    {
        if (AppConst.isBussiness || AppConst.DebugMode)
            return;

        if (Application.platform == RuntimePlatform.Android)
        {
#if SDK_BILIBILI
            androidObject.CallStatic("logout");
#elif SDK_XN
            androidObject.Call("loginOut");
#endif
        }
        else if (Application.platform == RuntimePlatform.IPhonePlayer)
        {
#if UNITY_IPHONE
            //loginOut();
#endif
        }

    }

    public void createRoleSDK(string roleinfo)
    {
        if (AppConst.isBussiness || AppConst.DebugMode)
            return;
        if (Application.platform == RuntimePlatform.Android)
        {
#if SDK_BILIBILI
            string[] strs = roleinfo.Split(',');
            string roleId=  strs[0];
            string roleName = strs[1];
            androidObject.CallStatic("createRole",roleName,roleId);
#elif SDK_XN
            string[] strs = roleinfo.Split(',');
            string roleId = strs[0];
            string roleName = strs[1];
            string serverName = strs[2];
            androidObject.Call("createRole", roleId,roleName,serverName,serverName);
#endif
        }
        else if (Application.platform == RuntimePlatform.IPhonePlayer)
        {
#if UNITY_IPHONE
            //createRole(roleinfo);
#endif
        }
    }

    public void startGameSDK(string roleinfo)
    {
        if (AppConst.isBussiness || AppConst.DebugMode)
            return;
        if (Application.platform == RuntimePlatform.Android)
        {
#if SDK_BILIBILI
            string[] strs = roleinfo.Split(',');
            string roleId = strs[0];
            string roleName = strs[1];
            androidObject.CallStatic("notifyZone",roleId,roleName);
#elif SDK_XN
            string[] strs = roleinfo.Split(',');
            string roleId = strs[0];
            string roleName =strs[1];
            string serverName = strs[2];
            int level = int.Parse(strs[3]);
            androidObject.Call("startGame", roleId,roleName,serverName,level);
#endif
        }
        else if (Application.platform == RuntimePlatform.IPhonePlayer)
        {
#if UNITY_IPHONE
            //startGame(roleinfo);
#endif
        }

    }

    public void upLevelSDK(string roleinfo)
    {
        if (AppConst.isBussiness || AppConst.DebugMode)
            return;

        if (Application.platform == RuntimePlatform.Android)
        {
#if SDK_BILIBILI
#elif SDK_XN
            androidObject.Call("upLevel", roleinfo);
#endif
        }
        else if (Application.platform == RuntimePlatform.IPhonePlayer)
        {
#if UNITY_IPHONE
            //upLevel(roleinfo);
#endif
        }

    }

    public void pay(long uid, string userName, string role, string serverId, int totalFee, int gameMoney, string outTradeNo, string subject, string body, string extrInfo, string notifyUrl, string orderSign)
    {
        if (AppConst.isBussiness || AppConst.DebugMode)
            return;
        if (Application.platform == RuntimePlatform.Android)
        {
#if SDK_BILIBILI
            androidObject.CallStatic("pay",uid,userName,role,serverId,totalFee,gameMoney,outTradeNo,subject,body,extrInfo,notifyUrl,orderSign);
#elif SDK_XN
#endif
        }
    }

    public void MissionBegin(string mission)
    {
        if (AppConst.isBussiness || AppConst.DebugMode)
            return;
        if (Application.platform == RuntimePlatform.Android)
        {
#if SDK_XN
            androidObject.Call("onBegin",mission);
#endif
        }
    }

    public void MissionComplect(string mission)
    {
        if (AppConst.isBussiness || AppConst.DebugMode)
            return;
        if (Application.platform == RuntimePlatform.Android)
        {
#if SDK_XN
            androidObject.Call("OnComplect",mission);
#endif
        }
    }

    public void MissionFail(string mission, string cause)
    {
        if (AppConst.isBussiness || AppConst.DebugMode)
            return;
        if (Application.platform == RuntimePlatform.Android)
        {
#if SDK_XN
            androidObject.Call("OnFail",mission,cause);
#endif
        }
    }



    //sdk传回
    public void SdkCallBack(string jsonstr)
    {
#if SDK_BILIBILI
        JsonData json = JsonMapper.ToObject (jsonstr);
        string callbackType = (string)json ["callbackType"];
        int code = (int)json ["code"];

        switch (callbackType)
        {
            case "Init":
                if(code ==SUCCESS_CODE)
                {
                    initSuccess();
                }
                break;
            case "Login":
                if(code ==SUCCESS_CODE)
                {
                    AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
                    AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
                    mAccountType  = jo.Get<int>("accountType");
                    JsonData data =JsonMapper.ToObject((string)json["data"]);
                    string uid = (string)data["uid"]+",,"+ (string)data["access_token"];
                    loginServer(uid);
                }
                break;
            case "Logout":
                if(code ==SUCCESS_CODE)
                {
                    sdklogout();
                }
                break;
            case "Register":
                if(code ==SUCCESS_CODE)
                {
                    loginAccount();
                }
                break;
            case "GetUserInfo":
                break;
            case "Pay":
                break;
            case "NotPayExit":
                if(code ==SUCCESS_CODE)
                {
                    Application.Quit();
                }
                break;
            case "AccountInvalid":
                if(code ==SUCCESS_CODE)
                {
                    sdklogout();
                }
                break;
            case "Exit":
                if(code ==SUCCESS_CODE)
                {
                    Application.Quit();
                }
                break;
        }


#elif SDK_XN
        Debug.LogWarning("SDKBACK:"+ jsonstr);
        JsonData json = JsonMapper.ToObject (jsonstr);
        string callbackType = (string)json ["callbackType"];
        int code = (int)json ["code"];

        switch (callbackType)
        {
            case "Login":
                if(code == SUCCESS_CODE)
                {
                    mAccountType = androidObject.Get<int>("accountType");
                    JsonData data =JsonMapper.ToObject((string)json["data"]);
                    string uid = (string)data["uid"]+","+(string)data["sign"];
                    loginServer(uid);
                }
                break;
            case "Logout":
                if(code == SUCCESS_CODE)
                {
                    sdklogout();
                }
                break;
            case "Message":
                break;
        }
#endif
    }
    /// <summary>
    /// 分享图片给微信好友
    /// </summary>
    /// <param name="jpgPath"></param>
    /// <param name="content"></param>
    public void ShareTextureToWXFriend(string jpgPath, string content)
    {
#if UNITY_ANDROID && !UNITY_EDITOR
        u8SDK.ShareToWXFriend(jpgPath, content);
#elif UNITY_IOS
        string[] paths = jpgPath.Split('/');
        string filePath = Util.DataPath + "share.jpg";
        if (paths.Length > 1)
        {
            filePath = Util.DataPath + paths[1];
        }
        Debug.Log("分享图片路径=1==" + filePath);
        byte[] bytes = System.IO.File.ReadAllBytes(filePath);
        ShareImgToWX(0, bytes, bytes.Length, content, content);
#endif

    }

    /// <summary>
    /// 分享图片到微信朋友圈
    /// </summary>
    /// <param name="jpgPath"></param>
    /// <param name="content"></param>
    public void ShareTextureToWXCircle(string jpgPath, string content)
    {
#if UNITY_ANDROID && !UNITY_EDITOR
        u8SDK.ShareToWXCircleOfFriend(jpgPath, content);
#elif UNITY_IOS
        string[] paths = jpgPath.Split('/');
        string filePath = Util.DataPath + "share.jpg";
        if (paths.Length > 1)
        {
            filePath = Util.DataPath + paths[1];
        }
        Debug.Log("分享图片路径=2==" + filePath);
        byte[] bytes = System.IO.File.ReadAllBytes(filePath);
        ShareImgToWX(1, bytes, bytes.Length, content, content);
#endif
    }



    /// <summary>
    /// 分享图片到新浪微博
    /// </summary>
    /// <param name="jpgPath"></param>
    /// <param name="content"></param>
    public void ShareTextureSinaWB(string jpgPath, string content)
    {
#if UNITY_ANDROID && !UNITY_EDITOR
        u8SDK.ShareToSinaWB(jpgPath, content);
#elif UNITY_IOS
        string[] paths = jpgPath.Split('/');
        string filePath = Util.DataPath + "share.jpg";
        if (paths.Length > 1)
        {
            filePath = Util.DataPath + paths[1];
        }
        Debug.Log("分享微博图片路径=2==" + filePath);
        byte[] bytes = System.IO.File.ReadAllBytes(filePath);
        ShareImgToWeibo(bytes, bytes.Length, content);
#endif
    }

    public void initSuccess()
    {
#if SDK_BILIBILI
        isInit = true;
        androidObject.CallStatic("login");
#endif
    }

    public void loginServer(string uid, string token, int channel,string subChannel)
    {
        LuaManager luaMgr = AppFacade.Instance.GetManager<LuaManager>(ManagerName.Lua);
        if (luaMgr != null)
        {


            LuaTable luaTable = luaMgr.GetTable("UILogin");
            if (luaTable != null)
            {
                Util.CallDisposeMethod("UILogin", "LoginSDKSucess", luaTable, uid, token , channel, subChannel);
                luaTable.Dispose();
            }
        }
        //Util.CallMethod("UILogin", "LoginSDKSucess", new object[] { uid, token });
    }

    public void sdklogout()
    {
        mAccountType = 0;
        Util.CallMethod("UIHeadInfo", "OnChangeAccClick", new object[] { });     //切换账号 登出账号
    }

    //U8初始化成功回调
    public void U8InitSuccess(string para)
    {
#if UNITY_IOS
        u8Init = true;
        LuaManager luaMgr = AppFacade.Instance.GetManager<LuaManager>(ManagerName.Lua);
        if (luaMgr != null)
        {
            LuaTable luaTable = luaMgr.GetTable("UILogin");
            if (luaTable != null)
            {
                Util.CallDisposeMethod("UILogin", "InitSDKSuccess", luaTable);
                luaTable.Dispose();
            }
        }
#endif
    }

    // 登录成功
    public void LoginInSuccess(string jsonStr)
    {
        TA.TABehavior.Track("u8sdk_login_success");
        //Debug.Log("C# LoginInSuccess" + jsonStr);
        JsonData json = JsonMapper.ToObject(jsonStr);
        string uid = (string)json["userID"];
        string token = (string)json["token"];
        int channel = (int)json["channal"];
        string subChannel = (string)json["subChannel"];
        //Debug.Log("LoginInSuccess  uid" + uid);
        //Debug.Log("LoginInSuccess  token" + token);
        //Debug.Log("LoginInSuccess  channel" + channel);
        loginServer(uid, token , channel, subChannel);
    }

    /// <summary>
    /// SDK账号切换，由sdk调用
    /// </summary>
    /// <param name="jsonStr"></param>
    public void SwitchAccount(string jsonStr)
    {
        TA.TABehavior.Track("Switch Account Success");
        
        LuaManager luaMgr = AppFacade.Instance.GetManager<LuaManager>(ManagerName.Lua);
        if (luaMgr != null)
        {
            LuaTable luaTable = luaMgr.GetTable("UILogin");
            if (luaTable != null)
            {
                Util.CallDisposeMethod("UILogin", "OnSwitchAccountSuccess", jsonStr);
                luaTable.Dispose();
            }
        }
    }
    public void ExitCallBackU8SDK(string jsonStr)
    {
        Debug.Log("=== ExitCallBackU8SDK === ExitCallBackU8SDK" + jsonStr);
        Util.CallMethod("SDKManager", "ExitCallBackU8SDK", new object[] { });     //安卓手机退出按钮，如果平台没有弹窗，触发此回调
    }

    public void LoginOutSuccess(string jsonStr)
    {
        
        Debug.Log("=== onLogout === LoginOutSuccess" + jsonStr);
        Util.CallMethod("SDKManager", "LoginOutSuccess", new object[] { });     //切换账号 登出账号
    }

    private int centerRedCount = 0;
    /// <summary>
    /// 客服中心红点数量回调
    /// </summary>
    public void AccountCenterRedPoint(string count)
    {
        centerRedCount = int.Parse(count);
        Util.CallMethod("SDKManager", "AccountCenterRedPoint", centerRedCount);
    }

    /// <summary>
    /// 客服中心红点数量
    /// </summary>
    public int GetAccountCenterRedCount()
    {
        return centerRedCount;
    }

    ////支付成功
    //public void PaySuccess(string str)
    //{
    //    LuaManager luaMgr = AppFacade.Instance.GetManager<LuaManager>(ManagerName.Lua);
    //    if (luaMgr != null)
    //    {
    //        //LuaTable luaTable = luaMgr.GetTable("UILogin");
    //        //if (luaTable != null)
    //        //{
    //        //    Util.CallDisposeMethod("UILogin", "LoginSDKSucess", luaTable, uid, token);
    //        //    luaTable.Dispose();
    //        //}
    //    }
    //}
    //接收从SDK发往Unity的数据
    public void SDK2Unity_CallbackHandle(string message)
    {
        string[] messageArr = message.Split('|');
        if(messageArr.Length == 2)
        {
            Util.CallMethod("SDKManager", "SDK2Unity_CallbackHandle", messageArr[0], messageArr[1]);
        }
    }

    //********************************************************************
#region 融云即时通讯 SDK
    protected  AndroidJavaObject mIMModule;
	protected AndroidJavaObject IMModule
	{
		get
		{
            if(u8SDK != null)
            {
                mIMModule = u8SDK.IMModule;
            }
			else if (mIMModule == null)
			{
                AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
                AndroidJavaObject mAndroidObject = jc.GetStatic<AndroidJavaObject>("currentActivity");
                mIMModule = mAndroidObject.Get<AndroidJavaObject>("imModule");
                
            }
			return mIMModule;
		}
	}
	
	public static bool IsInit_IM = false;               //在整个应用程序全局，只需要调用一次 init 方法
    
    //**** Unity → SDK *************
    /// <summary>
    /// 初始化融云SDK
    /// </summary>
    /// <param name="appKey">从本地游戏服务器端获得的 appKey</param>
    public void CallIM_Init(string appKey)
    {
		//Debug.LogError("[c#CallIM_Init]" + IsInit_IM + ","+ Application.platform);
		if (Application.platform == RuntimePlatform.Android)
		{
			if (IsInit_IM)
			{
				return;
			}
			IsInit_IM = true;
			IMModule.Call("CallIM_Init", appKey);
		}
#if UNITY_IPHONE
        {
            if (IsInit_IM)
            {
                return;
            }
            IsInit_IM = true;
            Debug.Log("======C# initIM");
            initIM(appKey);
        }
#endif
	}

    /// <summary>
    /// 连接融云服务器
    /// </summary>
    /// <param name="IM_Token">从本地游戏服务器端获得的 token</param>
    public void CallIM_Connect(string IM_Token)
    {
		if (Application.platform == RuntimePlatform.Android)
		{
			//Debug.LogError("[c#CallIM_Connect]" + IM_Token);
			IMModule.Call("CallIM_Connect", IM_Token);
		}
#if UNITY_IPHONE
        {
            Debug.Log("======C# connectIM");
            connectIM(IM_Token);
        }
#endif
    }

    /// <summary>
    /// 断开融云服务器连接
    /// </summary>
    /// <param name="isReceiveNewMessage">是否接收新消息的推送通知</param>
    public void CallIM_Disconnect(bool isReceiveNewMessage = true)
    {
		//if (Application.platform != RuntimePlatform.Android && Application.platform != RuntimePlatform.IPhonePlayer)
		//{
		//	return;
		//}
		if (isReceiveNewMessage)
        {
            if (Application.platform == RuntimePlatform.Android)
            {
                // 断开融云服务器连接，如果有新消息时，仍能收到推送通知
                IMModule.Call("CallIM_Disconnect");
            }
#if UNITY_IPHONE
            {
                disconnectIM();
            }
#endif
        }
        else
        {
            if (Application.platform == RuntimePlatform.Android)
            {
                // 完全断开融云服务器连接，如果有新消息，不会收到任何推送通知
                IMModule.Call("CallIM_Logout");
            }
#if UNITY_IPHONE
            {
                logoutIM();
            }
#endif
        }
    }

    /// <summary>
    /// 重连设备，默认false。设置 enable 为 true 时，SDK 重连的时候发现此时已有别的设备连接成功，不再强行踢出已有设备，而是踢出重连设备。
    /// 注：此功能首先需要客户提工单，在服务端开通此功能后，客户端调用该方法才生效
    /// </summary>
    /// <param name="enable">是否踢出重连设备</param>
    public void CallIM_SetReconnectKickEnable(bool enable)
    {

        IMModule.Call("CallIM_SetReconnectKickEnable", enable);
    }

    /// <summary>
    /// 设置个人信息
    /// </summary>
    /// <param name="userId">从本地游戏服务器获取的玩家id</param>
    /// <param name="userName">从本地游戏服务器获取的玩家名</param>
    /// <param name="portraitUrl">从本地游戏服务器获取的头像url</param>
    public void CallIM_SetMyselfUserInfo(string userId,string userName,string portraitUrl,string extra)
    {
		if (Application.platform == RuntimePlatform.Android)
		{
			IMModule.Call("CallIM_SetMyselfUserInfo", userId, userName, portraitUrl, extra);
		}
#if UNITY_IPHONE
        {
            setMySelfUserInfo(userId, userName, portraitUrl, extra);
        }
#endif
    }
	public void CallIM_EnableLog(bool enable)
	{
		if (Application.platform == RuntimePlatform.Android)
		{
			IMModule.Call("EnableLog", enable);
		}
	}
    /// <summary>
    /// 发送文本消息
    /// </summary>
    /// <param name="content">文字消息的文字内容，包括表情。</param>
    /// <param name="targetId">单聊 → receiverUserId (发送者id) </param>
    /// <param name="targetId">群组 → groupId (群id)</param>
    /// <param name="targetId">聊天室 →  chatRoomId</param>
    /// <param name="conversationType">ConversationType枚举会话类型</param>
    public void CallIM_SendTextMessage(string content, string targetId, ConversationType conversationType)
    {
		if (Application.platform == RuntimePlatform.Android)
		{
			IMModule.Call("CallIM_SendTextMessage", content, targetId, (int)conversationType);
		}
#if UNITY_IPHONE
        {
            sendMessageIM(content, targetId, (int) conversationType);
        }
#endif
    }

    /// <summary>
    /// 发送图片消息
    /// </summary>
    /// <param name="localImagePath">选择手机端本地图片</param>
    /// <param name="targetId">单聊 → receiverUserId (发送者id) </param>
    /// <param name="targetId">群组 → groupId (群id)</param>
    /// <param name="targetId">聊天室 →  chatRoomId</param>
    /// <param name="conversationType">ConversationType枚举会话类型</param>
    public void CallIM_SendImageMessage(string localImagePath, string targetId, ConversationType conversationType)
    {
		if (Application.platform == RuntimePlatform.Android)
		{
			IMModule.Call("CallIM_SendImageMessage", localImagePath, targetId, (int)conversationType);
		}
    }

    /// <summary>
    /// 分页拉取本地会话列表
    /// </summary>
    /// <param name="timeStamp">时间戳，获取从此时间戳往前的会话，第一次传 0</param>
    /// <param name="count">每页数量, 最大为 10 条</param>
    /// <param name="conversationType">会话类型</param>
    public void CallIM_GetConversationListByPage(long timeStamp,int count, ConversationType conversationType)
    {
		if (Application.platform == RuntimePlatform.Android)
		{
			IMModule.Call("CallIM_GetConversationListByPage", timeStamp, count, (int)conversationType);
		}
    }

    /// <summary>
    /// 历史消息获取
    /// </summary>
    /// <param name="targetId">单聊 → receiverUserId (发送者id) </param>
    /// <param name="targetId">群组 → groupId (群id)</param>
    /// <param name="targetId">聊天室 →  chatRoomId</param>
    /// <param name="conversationType">会话类型.</param>
    /// <param name="lastMessageId">当前消息列表中 sendTime 最小的消息ID. ID 不存在时, 应设置为-1</param>
    /// <param name="count">每页消息的数量. 每页数量最多 20 条</param>
    public void CallIM_GetHistoryMessages(string targetId, ConversationType conversationType, long lastMessageId, int count)
    {
		if (Application.platform == RuntimePlatform.Android)
		{
			IMModule.Call("CallIM_GetHistoryMessages", targetId, (int)conversationType, lastMessageId, count);
		}
#if UNITY_IPHONE
        {
            getHistoryMessagesIM(targetId, (int) conversationType, lastMessageId, count);
        }
#endif
    }

    /// <summary>
    /// 删除会话
    /// </summary>
    /// <param name="targetId">单聊 → receiverUserId (发送者id) </param>
    /// <param name="targetId">群组 → groupId (群id)</param>
    /// <param name="targetId">聊天室 →  chatRoomId</param>
    /// <param name="conversationType">ConversationType枚举会话类型</param>
    public void CallIM_RemoveConversation(string targetId, ConversationType conversationType)
    {
		if (Application.platform == RuntimePlatform.Android)
		{
			IMModule.Call("CallIM_RemoveConversation", targetId, (int)conversationType);
		}
#if UNITY_IPHONE
        {
            removeConversation(targetId, (int)conversationType);
        }
#endif
    }

    /// <summary>
    /// 更新接收状态
    /// </summary>
    /// <param name="messageId">id</param>
    /// <param name="isRead">是否已读</param>
    /// <param name="oldFlag">原来保存的flag</param>
    public void CallIM_RefreshReceivedStatus(int messageId,bool isRead,int oldFlag)
    {
		if (Application.platform == RuntimePlatform.Android)
		{
			int _readFlag = (isRead ? 1 : 0);
			int _newFlag = oldFlag | _readFlag;
			IMModule.Call("CallIM_RefreshReceivedStatus", messageId, _newFlag);
		}
    }

    /// <summary>
    /// 加入聊天室
    /// 如果聊天室不存在，SDK 会创建聊天室并加入，如果已存在，则直接加入
    /// </summary>
    /// <param name="chatRoomId">聊天室 ID</param>
    /// <param name="defMessageCount">拉取聊天消息记录数.1. -1 表示不获取任何历史消息;2. 0 表示使用 sdk 默认的设置（默认为10 条）;3. 获取的消息数量最大值为 50 条</param>
    public void CallIM_JoinChatRoom(string chatRoomId,int defMessageCount)
    {
		if (Application.platform == RuntimePlatform.Android)
		{
			IMModule.Call("CallIM_JoinChatRoom", chatRoomId, defMessageCount);
		}
#if UNITY_IPHONE
        {
            joinChatRoom(chatRoomId, defMessageCount);
        }
#endif
    }

    /// <summary>
    /// 退出聊天室
    /// </summary>
    /// <param name="chatRoomId">聊天室 ID</param>
   public void CallIM_QuitChatRoom(string chatRoomId)
    {
		if (Application.platform == RuntimePlatform.Android)
		{
			IMModule.Call("CallIM_QuitChatRoom", chatRoomId);
		}
#if UNITY_IPHONE
        {
            quitChatRoom(chatRoomId);
        }
#endif
    }
	public void CallIM_GetChatRoomInfo(string roomId, int defMemberCount)
	{
		if (Application.platform == RuntimePlatform.Android)
		{
			IMModule.Call("CallIM_GetChatRoomInfo", roomId, defMemberCount);
		}
#if UNITY_IPHONE
        {
            getChatRoomInfo(roomId, defMemberCount);
        }
#endif
	}
	//**** SDK → Unity *************
	/// <summary>
	/// 连接融云服务器成功
	/// </summary>
	/// <param name="userId">我自己的 id </param>
	public void IMCallback_ConnectSuccess(string userId)
    {
        //向服务器请求 myselfUserInfo
        Util.CallMethod("SDKManager", "ReqMyselfUserInfo", new object[] { userId });
    }
	public void IMCallback_ConnectFailed(string id)
	{
		//向服务器请求 myselfUserInfo
		Util.CallMethod("SDKManager", "IMCallback_ConnectFailed", id);
	}
	public void IMCallback_Handle(string message)
	{
		Util.CallMethod("SDKManager", "IMCallback_Handle", message);
	}
	public void IMCallback_GetHistoryTextMessagesSuccess(string messageJson)
	{
		Util.CallMethod("SDKManager", "IMCallback_ReceiveTextMessage", messageJson);
	}
	///接收实时或者离线文本消息
	public void IMCallback_ReceiveTextMessage(string messageJson)
    {
        //Debug.Log("C# IMCallback_ReceiveTextMessage:" + messageJson);
		Util.CallMethod("SDKManager", "IMCallback_ReceiveTextMessage", messageJson);
		//Dictionary<string, object> _messageDic = Util.JsonToDictionary(messageJson);
		//TODO ...
	} 

    //接收实时或者离线图片消息
    public void IMCallback_ReceiveImageMessage(string messageJson)
    {
        //Debug.Log("C# IMCallback_ReceiveImageMessage:" + messageJson);
        //Dictionary<string, object> _messageDic = Util.JsonToDictionary(messageJson);
        //TODO ...
    }

    //分页拉取本地会话列表 Callback
    public void IMCallback_GetConversationListByPageSuccess(string conversationJson)
    {
        //Debug.Log("C# IMCallback_GetConversationListByPageSuccess:" + conversationJson);
        //Dictionary<string, object> _conversationDic = Util.JsonToDictionary(conversationJson);
        //TODO ...
    }

    //发送文本信息返回
    public void IMCallback_SendTextMessageSuccess(string jsonObject)
    {
        //Debug.Log("C# IMCallback_SendImageMessageSuccess:" + jsonObject);
        //Dictionary<string, object> _conversationDic = Util.JsonToDictionary(jsonObject);

        // TODO ...
    }

    //发送图片信息返回
    public void IMCallback_SendImageMessageSuccess(string jsonObject)
    {
        //Debug.Log("C# IMCallback_SendImageMessageSuccess:" + jsonObject);
        //Dictionary<string, object> _conversationDic = Util.JsonToDictionary(jsonObject);

        // TODO ...
    }

    //删除会话
    public void IMCallback_RemoveConversationSuccess(string jsonObject)
    {
        //Debug.Log("C# IMCallback_RemoveConversationSuccess:" + jsonObject);
        //Dictionary<string, object> _conversationDic = Util.JsonToDictionary(jsonObject);

        // TODO ...
    }
	public void IMCallback_GetChatRoomInfo(string json)
	{
		Util.CallMethod("SDKManager", "IMCallback_GetChatRoomInfo", json);
	}


	public enum ConversationType
    {
        NONE = 0,
        PRIVATE = 1,                //单聊
        DISCUSSION = 2,             //已废弃
        GROUP = 3,                  //群聊
        CHATROOM = 4,               //聊天室
        CUSTOMER_SERVICE = 5,       //客服
        SYSTEM = 6,                 //系统
        APP_PUBLIC_SERVICE = 7,
        PUBLIC_SERVICE = 8,
        PUSH_SERVICE = 9,
        ENCRYPTED = 11,
        RTC_ROOM = 12,
    }

#endregion

#region 分享回调
    /// <summary>
    /// 微信分享回调
    /// </summary>
    /// <param name="message"></param>
    public void ShareToWXCallBack(string message)
    {
        int errCode = int.Parse(message);
        Util.CallMethod("ShareManager", "OnWXShareCallBack", errCode);
    }

    public void ShareToWeiBoCallBack(string message)
    {
        int errCode = int.Parse(message);
        Util.CallMethod("ShareManager", "OnWBShareCallBack", errCode);
    }

#endregion

    public void SetiOSAppIconBadgeNumber(int number = 0)
    {
#if UNITY_IPHONE && !UNITY_EDITOR
        setIconBadgeNumber(number);
#endif
    }

    public void GoToTaptapMoment()
    {
        Debug.Log("=========GoToTaptapMoment========");
        TapMoment.Open(Orientation.ORIENTATION_PORTRAIT);
    }

    /// <summary>
    /// 是否支持用户中心控制
    /// </summary>
    public bool GetSupportAccountCenter()
    {
        bool b = false;
#if UNITY_ANDROID && !UNITY_EDITOR
        b = u8SDK.u8SdkModule.Call<bool>("SupportShowCenter");
#elif UNITY_IPHONE && !UNITY_EDITOR
         b = true;
#endif
        return b;
    }
    
    /// <summary>
    /// 官网包显示sdk用户中心
    /// </summary>
    public void ShowAccountCenter()
    {
#if UNITY_ANDROID && !UNITY_EDITOR
        u8SDK.u8SdkModule.Call("ShowAccountCenter");
#elif UNITY_IOS
        ShowAccountCenterIOS();
#endif
    }

    /// <summary>
    /// 获取极光id
    /// </summary>
    /// <returns></returns>
    public string GetJpushRegistrationID()
    {
#if UNITY_ANDROID && !UNITY_EDITOR
        return u8SDK.u8SdkModule.Call<string>("GetJpushRegistrationID");
#else
        return "";
#endif
    }

#region iOS Widget相关
    /// <summary>
    /// 初始化widget数据
    /// </summary>
    /// <param name="nick">昵称</param>
    /// <param name="tick">上一次领取挂机奖励事件戳（秒）</param>
    /// <param name="maxHangTime">最大挂机时长（秒）</param>
    /// <param name="power">战力</param>
    /// <param name="stage">主线关卡进度</param>
    /// <param name="tower">热砂遗迹进度</param>
    /// <param name="heros">解锁英雄数量</param>
    public void InitWidgetData(string nick, long tick, int maxHangTime, long power, int stage, int tower, int heros)
    {
#if UNITY_IPHONE && !UNITY_EDITOR
        initUserData(nick, tick, maxHangTime, power, stage, tower, heros);
#endif
    }

    /// <summary>
    /// 更新玩家昵称
    /// </summary>
    /// <param name="nick">昵称</param>
    public void SetWidgetUserNick(string nick)
    {
#if UNITY_IPHONE && !UNITY_EDITOR
        setUserNick(nick);
#endif  
    }

    /// <summary>
    /// 更新挂机时间
    /// </summary>
    /// <param name="tick">上一次领取挂机奖励事件戳（秒）</param>
    /// <param name="maxHangTime">最大挂机时长（秒）</param>
    public void SetWidgetGetRewardTick(long tick, int maxHangTime)
    {
#if UNITY_IPHONE && !UNITY_EDITOR
        setUserGetRewardTick(tick, maxHangTime);
#endif  
    }

    /// <summary>
    /// 更新玩家战力
    /// </summary>
    /// <param name="power">战力</param>
    public void SetWidgetUserPower(long power)
    {
#if UNITY_IPHONE && !UNITY_EDITOR
        setUserPower(power);
#endif  
    }

    /// <summary>
    /// 更新主线关卡进度
    /// </summary>
    /// <param name="stage">主线关卡进度</param>
    public void SetWidgetUserStage(int stage)
    {
#if UNITY_IPHONE && !UNITY_EDITOR
        setUserStage(stage);
#endif  
    }

    /// <summary>
    /// 更新热砂遗迹进度
    /// </summary>
    /// <param name="tower">热砂遗迹进度</param>
    public void SetWidgetUserTower(int tower)
    {
#if UNITY_IPHONE && !UNITY_EDITOR
        setUserTower(tower);
#endif  
    }

    /// <summary>
    /// 更新英雄数量
    /// </summary>
    /// <param name="heros">英雄数量</param>
    public void SetWidgetUserHeros(int heros)
    {
#if UNITY_IPHONE && !UNITY_EDITOR
        setUserHeros(heros);
#endif  
    }

    /// <summary>
    /// widget跳转游戏功能页面
    /// </summary>
    /// <param name="viewId">页面id</param>
    public void WidgetToView(int viewId)
    {
#if UNITY_IPHONE && !UNITY_EDITOR
        Util.CallMethod("SDKManager", "WidgetToView", viewId);
#endif 
    }
#endregion
}

